'use strict';

const BaseService = require('./base');
const modelName = 'Balance'
class RouterService extends BaseService {
    constructor(ctx) {
        super(ctx, modelName);
    }

    async update(id, data) {
        const { ctx } = this;
        if (data.status === 0) {
            const result = await this.findOne(id);
            // 用户
            const userId = result.dataValues.user_id
            // 金额
            const amount = data.amount
            // 查找用户
            const user = await ctx.service.user.findOne(userId)
            // balance
            const balance = user.dataValues.balance
            // 退回
            const newBalance = parseFloat(balance) + parseFloat(amount)
            await ctx.service.user.update(userId, { balance: newBalance })
            await super.update(id, data);
        } else {
            await super.update(id, data);
        }

        return true;
    }

    // 提现
    async create2(data) {
        const { ctx } = this;
        // 用户
        const userId = data.user_id
        // 金额
        const amount = data.amount
        // 查找用户
        const user = await ctx.service.user.findOne(userId)
        // balance
        const balance = user.dataValues.balance
        // 余额不足
        if (parseFloat(balance) < parseFloat(amount)) {
            return false
        }
        // 余额
        const newBalance = parseFloat(balance) - parseFloat(amount)
        await ctx.service.user.update(userId, { balance: newBalance })
        await super.create(data);
        return true
    }
}


module.exports = RouterService;
